<template>
  <div class="listen-identify">
    <el-skeleton :rows="5" animated v-if="loading" />
    <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" />
    <div v-else>
      <MyHeaderInLesson :lesson="lesson" :moduleName="'听辨练习'" />

      <AudioControls
        :current-index="currentSentenceIndex"
        :total-items="lesson.content.length"
        :is-playing="isPlaying"
        @previous="playPrevious"
        @toggle-playback="togglePlayback"
        @next="playNext"
        @speed-change="changeSpeed"
      />

      <!-- 句子选择下拉框 -->
      <div class="sentence-selector">
        <el-select v-model="currentSentenceIndex" placeholder="请选择句子" style="width: 100%" class="mosaic-text">
          <el-option
            v-for="(sentence, index) in lesson.content"
            :key="index"
            :label="`${index + 1}. ${sentence.english}`"
            :value="index"
          >
            <div class="sentence-option">
              <span class="sentence-number">{{ index + 1 }}.</span>
              <span class="sentence-text">{{ sentence.english }}</span>
            </div>
          </el-option>
        </el-select>
      </div>

      <!-- 听辨练习控制选项 -->
      <div class="listen-options">
        <el-button @click="playCurrentSentence" class="control-button"> 朗读 </el-button>
        <el-button @click="showAllWords" class="control-button"> 全显 </el-button>
        <el-button @click="resetExercise" class="control-button primary"> 重置 </el-button>
      </div>

      <!-- 中文翻译显示 -->
      <div class="chinese-translation">
        {{ currentSentence.chinese }}
      </div>

      <!-- 英文句子显示区域 -->
      <div class="english-sentence-area">
        <h3>点击下面的空格来显示对应的单词</h3>

        <div class="sentence-display">
          <div v-for="(item, index) in sentenceItems" :key="index">
            <span v-if="item.type === 'word'" class="word-container" @click="revealWord(item.wordIndex)">
              <div v-if="displayedWords[item.wordIndex].revealed" class="word-revealed">
                {{ item.text }}
              </div>
              <div v-else class="word-hidden">___</div>
            </span>
            <span v-else class="punctuation-item">
              {{ item.text }}
            </span>
          </div>
        </div>
      </div>

      <!-- 完成提示 -->
      <div v-if="isCompleted" class="completion-message">
        <el-alert title="恭喜！您已显示所有单词！" type="success" show-icon center />
      </div>
    </div>
  </div>
</template>

<script>
import AudioControls from '../components/text-study/AudioControls.vue'
import { ElSkeleton, ElAlert, ElPageHeader, ElButton } from 'element-plus'
import { lessonLoader } from '../mixins/lessonLoader.js'
import MyHeaderInLesson from '../components/layout/MyHeaderInLesson.vue'
import KeyboardAudio from '../utils/keyboardAudio.js'

export default {
  name: 'ListenIdentify',
  components: {
    AudioControls,
    ElSkeleton,
    ElAlert,
    ElPageHeader,
    ElButton,
    MyHeaderInLesson
  },
  mixins: [lessonLoader],
  data() {
    return {
      currentSentenceIndex: 0,
      isPlaying: false,
      // 练习相关数据
      sentenceItems: [], // 句子项（包括单词和标点）
      displayedWords: [], // 显示的单词状态
      correctWords: [], // 正确单词
      isCompleted: false,
      sentenceEndTime: 0 // 句子结束时间
    }
  },
  computed: {
    currentSentence() {
      if (!this.lesson || !this.lesson.content || this.lesson.content.length === 0) {
        return { english: '', chinese: '' }
      }

      this.$nextTick(() => {
        this.initExercise()
      })
      return this.lesson.content[this.currentSentenceIndex] || { english: '', chinese: '' }
    }
  },
  async mounted() {
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', this.playPrevious)
    KeyboardAudio.register('ArrowRight', this.playNext)
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    // Check for sentence_id parameter and set current sentence index
    const sentenceId = this.$route.query.sentence_id
    if (sentenceId && !isNaN(sentenceId) && sentenceId > 0) {
      // Convert to 0-based index
      const index = parseInt(sentenceId) - 1
      // Make sure it's within bounds
      if (index < this.lesson.content.length) {
        this.currentSentenceIndex = index
        // Initialize exercise for the specified sentence
        this.$nextTick(() => {
          this.initExercise()
        })
      }
    }
  },
  beforeUnmount() {
    KeyboardAudio.destroy()
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
  },
  methods: {
    initExercise() {
      if (!this.currentSentence) {
        return
      }
      // 获取当前句子的英文文本
      const sentenceText = this.currentSentence.english
      // 将句子拆分为单词和标点符号，使用空格分割并去除末尾标点
      const tokens = this.tokenizeSentence(sentenceText)

      // 创建句子项数组
      this.sentenceItems = []
      this.correctWords = []

      let wordIndex = 0
      tokens.forEach((token) => {
        // 判断是单词还是标点符号
        if (this.isWord(token)) {
          // 单词
          this.sentenceItems.push({
            type: 'word',
            text: token,
            wordIndex: wordIndex
          })
          this.correctWords.push(token)
          wordIndex++
        } else {
          // 标点符号
          this.sentenceItems.push({
            type: 'punctuation',
            text: token
          })
        }
      })

      // 创建显示单词数组，默认都隐藏
      this.displayedWords = this.correctWords.map((word) => ({
        text: word,
        revealed: false
      }))

      this.isCompleted = false
    },

    // 将句子分割为单词和标点符号的函数
    tokenizeSentence(sentence) {
      // 先按空格分割
      const parts = sentence.split(' ')
      const tokens = []

      parts.forEach((part) => {
        // 移除末尾的标点符号作为单词
        const word = part.replace(/[.!?,"'();:]$/, '')
        if (word) {
          tokens.push(word)
        }

        // 如果原部分包含末尾标点符号，则单独作为一个token
        const punctuationMatch = part.match(/[.!?,"'();:]$/)
        if (punctuationMatch) {
          tokens.push(punctuationMatch[0])
        }
      })

      return tokens
    },

    // 判断是否为单词的函数
    isWord(token) {
      // 不是标点符号的就是单词
      return !/[.!?,"'();:]/.test(token)
    },

    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        this.initExercise()
      }
    },

    togglePlayback() {
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.playCurrentSentence()
      }
    },

    playNext() {
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        this.initExercise()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return

      const sentence = this.lesson.content[this.currentSentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.audio.currentTime = sentence.startTime
        this.sentenceEndTime = sentence.endTime
        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
      }
    },

    onAudioEnded() {
      this.isPlaying = false
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    revealWord(wordIndex) {
      // 显示指定索引的单词
      if (wordIndex < this.displayedWords.length && !this.displayedWords[wordIndex].revealed) {
        this.displayedWords[wordIndex].revealed = true
        this.checkCompletion()
      }
    },

    showAllWords() {
      // 显示所有单词
      this.displayedWords.forEach((word) => {
        word.revealed = true
      })
      this.isCompleted = true
    },

    checkCompletion() {
      // 检查是否所有单词都已显示
      const allRevealed = this.displayedWords.every((word) => word.revealed)
      if (allRevealed) {
        this.isCompleted = true
      }
    },

    resetExercise() {
      this.initExercise()
    }
  }
}
</script>

<style scoped lang="scss">
@use '../assets/styles/listenIdentify.scss';

.sentence-selector {
  margin: 20px 0;

  :deep(.el-select) {
    width: 100%;
  }

  :deep(.el-select-dropdown__item) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .sentence-option {
    display: flex;
    align-items: center;
    overflow: hidden;
    text-overflow: ellipsis;

    .sentence-number {
      flex-shrink: 0;
      margin-right: 8px;
      font-weight: bold;
    }

    .sentence-text {
      flex-grow: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>